﻿var _iconA = "CA9DB050-8DC7-4CDC-819F-9C185E724183";
var _iconB = "7218C75D-2AE5-4A8F-B6FF-E45D5017723F";
var _mush = "C4A9BF33-42DA-4976-ACFC-B3DB3DB3ECB3";

$(document).ready(function () {
    var randomnumber = Math.floor(Math.random() * 3);

    switch (randomnumber) {
        case 0:
            _iconA = "A4F5F1AC-43E0-4A39-8D86-1E510465837F";
            _iconB = "3ED2B825-CE5C-41B1-A139-AB517F55B87E";
            _mush = "116D6138-5473-48BC-ACA8-D112C2951AD4";
            break;
        case 1:
            _iconA = "AE907743-FCDA-4D9D-AE1F-B6E75E34A647";
            _iconB = "3189F574-329B-45A3-A5DA-23A51974E045";
            _mush = "ED517214-138F-4D22-AF4F-DA3BBE1919D2";
            break;
        case 2:
            _iconA = "CA9DB050-8DC7-4CDC-819F-9C185E724183";
            _iconB = "7218C75D-2AE5-4A8F-B6FF-E45D5017723F";
            _mush = "C4A9BF33-42DA-4976-ACFC-B3DB3DB3ECB3";
    }

    GameBoard.Board = AzureGames.AmazonsBoard.SetModel(GameBoard.BoardJSON);

    GameBoard.IconAUrl = agames.getRelativeEndpointUrl('/Game/GetResource?resourceID=' + _iconA + '&contentType=image%2Fjpeg');
    GameBoard.IconBUrl = agames.getRelativeEndpointUrl('/Game/GetResource?resourceID=' + _iconB + '&contentType=image%2Fjpeg');
    GameBoard.IconCUrl = agames.getRelativeEndpointUrl('/Game/GetResource?resourceID=' + _mush + '&contentType=image%2Fjpeg');

    displayBoard();

    if (GameBoard.Board.PlayerIDs.length == 1) {
        // game is not ready to play
        $('#finalBanner').removeClass();
        $('#finalBanner').addClass('show');
        $('#finalBanner').text('Waiting for player to join');
        GameBoard.IsPlayersTurn = false;
    }

    // comment in this logic to start polling instead of websockets
    //if (GameBoard.IsPlayersTurn == false) {
    //    setTimeout("AzureGames.GetBoard()", 2000);
    //}
});

function displayBoard() {
    GameBoard.IsPlayersTurn = GameBoard.Board.PlayerIDs[GameBoard.Board.currentPlayer] == GameBoard.UserID;

    for (var r = 0; r < 10; r++)
        for (var c = 0; c < 10; c++) {
            var loc = '#Row' + r + 'Col' + c;
            setModel(loc, GameBoard.Board.board[r][c]);
        }

    if (GameBoard.Board.movedPiece != null) {
        var l = '#Row' + GameBoard.Board.movedPiece.row + 'Col' + GameBoard.Board.movedPiece.column;
        var moves = GameBoard.Board.getValidMoves(GameBoard.Board.movedPiece.row, GameBoard.Board.movedPiece.column);
        displayValidMoves(l, moves);
    }

    // detect if the game is over
    if (GameBoard.Board.currentPhase > 2) {
        $('#finalBanner').removeClass();
        $('#finalBanner').addClass('show');
        if (GameBoard.Board.currentPhase == 3)
            $('#finalBanner').text('Player 0 Wins!!!');
        else
            $('#finalBanner').text('Player 1 Wins!!!');
    }
    else {
        $('#finalBanner').addClass('noShow');
    }
}


function setModel(location, model) {
    var div = $(location);
    switch (model) {
        case 2:
            // clear any image
            div.empty();
            break;
        case 1:
            div.empty();
            div.prepend('<img class="img highlightit" src="' + GameBoard.IconAUrl + '" alt="1" onClick="modelClick(\'' + location + '\')" />');
            break;
        case 0:
            div.empty();
            div.prepend('<img class="img highlightit" src="' + GameBoard.IconBUrl + '" alt="2" onClick="modelClick(\'' + location + '\')" />');
            break;
        case 3:
            div.empty();
            div.prepend('<img class="img highlightit" src="' + GameBoard.IconCUrl + '" alt="3" />');
            break;
    }
}

function getModelAtLocation(location) {
    var div = $(location);

    if (div.length > 0) {
        switch (div.children(0).attr('alt')) {
            case "1": return 1;
            case "2": return 0;
            case "3": return 3;
            default: return 2;
        }
    }
    else
        return 2;
}

function modelClick(location) {
    if (GameBoard.IsPlayersTurn) {
        if (GameBoard.Board.currentPhase == 0 && getModelAtLocation(location) == GameBoard.Board.currentPlayer) {
            var row = parseInt(location.substring(4, 5));
            var col = parseInt(location.substring(8, 9));
            var moves = GameBoard.Board.getValidMoves(row, col);
            displayValidMoves(location, moves);
        }
    }
}

function displayValidMoves(location, moves) {
    if (GameBoard.ModelSelected != undefined)
        if (GameBoard.ModelSelected.length > 0)
            clearModelSelected();

    GameBoard.ModelSelected = location;

    var cssClass = $(location).attr("class").substring(0, 6);

    $(location).removeClass();
    $(location).addClass(cssClass + 's');

    for (var move in moves) {
        var loc = '#Row' + moves[move].row + 'Col' + moves[move].column;
        cssClass = $(loc).attr("class").substring(0, 6);
        $(loc).removeClass();
        $(loc).addClass(cssClass + 's');
    }
}


function divClick(location) {
    if (GameBoard.ModelSelected != undefined)
        if (GameBoard.ModelSelected.length > 0) {
            location = '#' + location;
            if (($('div' + location).hasClass("empty1s") == true || $('div' + location).hasClass("empty2s") == true) && getModelAtLocation(location) == 2) {
                if (GameBoard.Board.currentPhase == 0) {
                    MovePiece(GameBoard.ModelSelected, location);
                }
                else {
                    ShootArrow(location);
                }
            }
        }
}

function clearModelSelected() {
    // clear previous selection
    $('div.empty1s').each(function () {
        $(this).removeClass();
        $(this).addClass("empty1");
    });

    $('div.empty2s').each(function () {
        $(this).removeClass();
        $(this).addClass("empty2");
    });

    GameBoard.ModelSelected = "";
}

function MovePiece(locationFrom, locationTo) {
    var model = getModelAtLocation(locationFrom);
    var from = {
        row: parseInt(locationFrom.substring(4, 5)),
        column: parseInt(locationFrom.substring(8, 9))
    };

    var to = {
        row: parseInt(locationTo.substring(4, 5)),
        column: parseInt(locationTo.substring(8, 9))
    };

    GameBoard.Board.moveModel(from, to, model);
    clearModelSelected();
    displayBoard();
}

function ShootArrow(location) {
    var to = {
        row: parseInt(location.substring(4, 5)),
        column: parseInt(location.substring(8, 9))
    };

    GameBoard.Board.shootArrow(to);

    // if the user is authenticated then save the game
    if (GameBoard.UserID != '00000000-0000-0000-0000-000000000000')
        AzureGames.UpdateGameBoard();

    displayBoard();
    clearModelSelected();
    GameBoard.IsPlayersTurn = false;

    document.body.style.cursor = 'wait';

    // if not playing against the AI then poll until other player has made a move
    if (AzureGames.Opponent == undefined) {
        // websockets will alert us when a player has joined
        // setTimeout("AzureGames.GetBoard()", 2000);
    }
    else
        setTimeout("AzureGames.Opponent(AzureGames.ApplyOpponentMove, GameBoard.Board, 1);", 10);

    //worker = new Worker('/Game/GetResource?resourceID=b9d3e9c5-a1cd-4ab1-92c7-e84a692c9916&contentType=text%2Fjavascript');
    //worker.addEventListener('message', AzureGames.ApplyOpponentMove, false);
    //worker.postMessage('magic');
}

AzureGames.UpdateGameBoard = function () {
    agames.dataManager.sendRequest({
        cache: false,
        type: 'POST',
        data: $.toJSON(GameBoard.Board.getModel()),
        url: '/Game/JsonUpdateBoard',
        contentType: 'application/json; charset=utf-8',
        success: function (data) {

        },
        error: function () {
            // try again
            setTimeout("AzureGames.UpdateGameBoard()", 1000);
        }
    });
}

AzureGames.ApplyOpponentMove = function (opponentsMove) {
    GameBoard.Board.applyMove(opponentsMove, 1);
    // if the user is authenticated then save the game
    if (GameBoard.UserID != '00000000-0000-0000-0000-000000000000')
        AzureGames.UpdateGameBoard();

    displayBoard();
    document.body.style.cursor = 'default';
}

AzureGames.OnBoardUpdated = function (data) {
    // ignore any old messages
    if (data.LastUpdatedDate != GameBoard.Board.LastUpdatedDate) {
        GameBoard.Board.updateModel(data);
        displayBoard();

        if (GameBoard.IsPlayersTurn == false)
            document.body.style.cursor = 'wait';
        else
            document.body.style.cursor = 'default';
    }
}

//AzureGames.GetBoard = function () {
//    agames.dataManager.sendRequest({
//        cache: false,
//        url: '/Game/JsonGetBoard/?gameId=' + GameBoard.GameID,
//        type: 'POST',
//        success: function (data) {            
//            if (data.LastUpdatedDate == GameBoard.Board.LastUpdatedDate) {
//              setTimeout("AzureGames.GetBoard()", 1000);
//            }
//            else {            
//                GameBoard.Board.updateModel(data);
//                displayBoard();

//                if (GameBoard.IsPlayersTurn == false)
//                    setTimeout("AzureGames.GetBoard()", 1000);
//                else
//                    document.body.style.cursor = 'default';
//            }
//        },
//        error: function () {
//            // try again
//            setTimeout("AzureGames.GetBoard()", 1000);
//        }
//    });
//}